package com.itsu.shirojwt.controller;

import java.util.List;

import javax.annotation.Resource;

import com.itsu.shirojwt.entity.User;
import com.itsu.shirojwt.response.ResObj;
import com.itsu.shirojwt.service.UserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.json.JSONUtil;

@RestController
public class MyController {

    @Resource
    private UserService userService;

    @GetMapping("/all")
    public List<User> getAll() {
        return userService.getAllUser();
    }

    @GetMapping("/exec")
    public int exec() {
        int num = 1 / 0;
        return num;
    }

    @PostMapping("/login")
    public ResObj login( User user) {
        System.out.println(JSONUtil.toJsonStr(user));
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
        subject.login(token);
        String tokenStr = userService.generateToken(user);
        return ResObj.ok("login success", tokenStr);
    }
}